import datetime
import re

from utils import restful
from .models import BookedTicket
from .serializers import BookedTicketSerializer


def booking_flight(request):
    data = {
        'user_id_id': int(request.POST.get('user_id')),
        'name': request.POST.get('name'),
        'flight_id_id': int(request.POST.get('flight_id')),
        'from_place': request.POST.get('from_place'),
        'to_place': request.POST.get('to_place'),
        'ticket_date': request.POST.get('start_time'),
        'class_type': int(request.POST.get('class_type')),
        'pay_status': request.POST.get('pay_status', '0'),
        'payment_amount': request.POST.get('payment_amount', 0),
        'create_time': datetime.datetime.now()
    }
    first_class_price = request.POST.get('first_class_price')
    economy_class_price = request.POST.get('economy_class_price')
    if request.POST.get('class_type') == '0':
        data['price'] = first_class_price
    else:
        data['price'] = economy_class_price
    try:
        result = BookedTicket(**data)
        result.save()
    except Exception as err:
        error = re.search('Duplicate entry', str(err))
        if error != None:
            return restful.params_error(message='您已预定该航班，请先支付或取消')
    except:
        return restful.params_error()

    return restful.ok()


def get_user_order(request):
    user_id = request.GET.get('user_id')
    result = BookedTicket.objects.filter(user_id_id=user_id)
    data = BookedTicketSerializer(result, many=True).data

    return restful.ok(data=data)


def modify_user_status(request):
    id = request.GET.get('id')
    status = request.GET.get('status')
    payment_amount = request.GET.get('payment_amount', 0)
    obj = BookedTicket.objects.get(id=id)
    obj.pay_status = status
    obj.payment_amount = payment_amount
    obj.save()

    return restful.ok()
